package com.weizhong.update.util;

import com.weizhong.update.R;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

/**
 * 弹窗辅助类
 *
 * @ClassName WindowUtils
 *
 *
 */
public class WindowUtils {

    private static final String LOG_TAG = "WindowUtils";
	protected  final String TAG = "WindowUtils";
    private  View mView = null;
    private  WindowManager mWindowManager = null;
    private  Context mContext = null;

    public  Boolean isShown = false;

    public int time = 5000;
    
    TextView textView;
    
    String apkpath = null;
    
    String packageName = null;
    /**
     * 显示弹出框
     *
     * @param context
     * @param view
     */
    public  void showPopupWindow(final Context context,String path,String packageName) {
        if (isShown) {
            Log.i(LOG_TAG, "return cause already shown");
            return;
        }

        this.packageName = packageName;
        apkpath = path;
        isShown = true;
        Log.i(LOG_TAG, "showPopupWindow");

        // 获取应用的Context
        mContext = context.getApplicationContext();
        // 获取WindowManager
        mWindowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);

        mView = setUpView(context);

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        // 类型
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

        // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT

        // 设置flag

        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
        params.flags = flags;
        // 不设置这个弹出框的透明遮罩显示为黑色
        params.format = PixelFormat.TRANSLUCENT;
        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
        // 不设置这个flag的话，home页的划屏会有问题

        params.width = LayoutParams.MATCH_PARENT;
        params.height = LayoutParams.MATCH_PARENT;

        params.gravity = Gravity.CENTER;

        mWindowManager.addView(mView, params);
        
        new Thread(new ThreadShow()).start();

        Log.i(LOG_TAG, "add view");

    }

    /**
     * 隐藏弹出框
     */
    public void hidePopupWindow() {
        Log.i(LOG_TAG, "hide " + isShown + ", " + mView);
        if (isShown && null != mView) {
        	Log.i(LOG_TAG, "hidePopupWindow");
            mWindowManager.removeView(mView);
            isShown = false;
        }

    }

    private static View setUpView(final Context context) {

    	Log.i(LOG_TAG, "setUp view");

        View view = LayoutInflater.from(context).inflate(R.layout.popupwindow,
                null);

        // 点击窗口外部区域可消除
        // 这点的实现主要将悬浮窗设置为全屏大小，外层有个透明背景，中间一部分视为内容区域
        // 所以点击内容区域外部视为点击悬浮窗外部
        final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的内容区域

        return view;

    }
    
    // handler类接收数据  
    Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  
            if (msg.what == 1) {  
            	Log.i(TAG, "handleMessage");
            	int remainTime = time/1000;
            	if(remainTime <= 0){
            		time = 0;
            	}
            	if ((mView != null) && (time != 0)){
            		textView = (TextView) mView.findViewById(R.id.title);
            		textView.setText("本应用即将更新，" + remainTime +"秒钟后将关闭"+ "");
            		time -= 1000;
            	}else if(mView == null){
					Log.i(TAG, "mView == null!");
				}else if ((mView != null) || (time == 0)) {
					Log.i(TAG, "mView != null! time == 0");
					hidePopupWindow();
					AppManager appManager = new AppManager(mContext);
					if(apkpath != null){
						Log.i(TAG, "强制安装");
						appManager.removeTast(packageName, false);
						appManager.installapp(apkpath,true);
					}
				}
            	if(remainTime <= 0){
            		time = 0;
            	}
            }  
        };  
    };  
  
    // 线程类  
    class ThreadShow implements Runnable {  
  
        @Override  
        public void run() {  
            // TODO Auto-generated method stub  
            while (time > 0) {  
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();  
                    msg.what = 1; 
                    handler.sendMessage(msg);
                    System.out.println("send...");  
                } catch (Exception e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                    System.out.println("thread error...");  
                }  
            }  
        }  
    }  
}